import { login, getInfo, getUserDetailById } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'

const getDefaultState = () => {
  return {
    token: getToken() || null,
    name: '',
    avatar: '',
    loading: false,
    userInfo: null
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: state => {
    removeToken()
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  LOGIN_TRUE_STATUS: state => {
    state.loading = true
  },
  LOGIN_FALSE_STATUS: state => {
    state.loading = false
  },
  SET_INFO (state, payload) {
    state.userInfo = payload
  }
}

const actions = {
  // 登录
  async login ({ commit }, userInfo) {
    commit('LOGIN_FALSE_STATUS')
    try {
      // 登录状态
      const res = await login(userInfo)
      setToken(res.data)
      commit('SET_TOKEN', res.data)
    } catch (error) {
      commit('LOGIN_FALSE_STATUS')
      throw new Error(error)
    } finally {
    }
  },

  // get user info
  async getInfo ({ commit }) {
    const res = await getInfo()
    const res2 = await getUserDetailById(res.data.userId)
    commit('SET_INFO', { ...res.data, ...res2.data })
  },
  logoOut ({ commit }) {
    commit('RESET_STATE')
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
